<?php


namespace common\logic;

use common\server\Server;
use common\server\Validate;
use operate\editing\topic\validate\ValidateAction;
use PharIo\Manifest\AuthorCollectionIterator;
use yii\base\Model;
use yii\db\ActiveQuery;

/**
 * Class Logic
 *
 * @package common\logic
 */
abstract class Logic extends Server
{

    /**
     * @return ActiveQuery
     */
    abstract protected function _getActiveQuery();

    /**
     * @param $condition
     * @param array $params
     * @param array $fields
     * @param array $columns
     * @return ActiveQuery
     */
    public function getQuery($condition = '', $params = [], $fields = [], $columns = [])
    {
        return $this->_getActiveQuery()->select($fields)->where($condition, $params)->orderBy($columns);
    }

    /**
     * @param $condition
     * @param array $params
     * @return int|string
     */
    public function getCount($condition='', $params = [])
    {
        return $this->getQuery($condition, $params)->count();
    }

    /**
     * @param $condition
     * @param array $params
     * @return int|string
     */
    public function getSum($field,$condition='',$params=[])
    {
        return $this->getQuery($condition, $params)->sum($field);
    }

    /**
     * @param $condition
     * @param array $params
     * @return array|null|\yii\db\ActiveRecord
     */
    protected function _get($condition='', $params = [])
    {
        return $this->getQuery($condition, $params)->limit(1)->one();
    }

    /**
     * @param $condition
     * @param array $params
     * @param array $fields
     * @param array $order
     * @return array|\yii\db\ActiveRecord[]
     */
    protected function _all($condition='', $params = [], $fields = [], $order = [])
    {
        return $this->getQuery($condition, $params, $fields, $order)->all();
    }

    /**
     * @param ActiveQuery $query
     * @return array|null|\yii\db\ActiveRecord
     */
    public function getWithQuery(ActiveQuery $query)
    {
        return $query->one();
    }

    /**
     * @param ActiveQuery $query
     * @return array|\yii\db\ActiveRecord[]
     */
    public function allWithQuery(ActiveQuery $query)
    {
        return $query->all();
    }

    public function getDataWithUrl($url,$is_post=true,$post_data=[]){
        $timeout = 15;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        if($is_post){
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
        }

        $res = curl_exec($ch);
        curl_close($ch);
        $res=json_decode($res);

        return $res;
    }
    
}